<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>服务商管理</h1>
      <p>管理平台支持的服务商，配置服务商参数和信息</p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 服务商名称 -->
          <div class="search-field">
            <label class="search-label">服务商名称:</label>
            <a-input
              v-model:value="searchForm.providerName"
              placeholder="请输入服务商名称"
              class="search-input"
              allowClear
              @press-enter="handleSearch"
            />
          </div>

          <!-- 服务商类型 -->
          <div class="search-field">
            <label class="search-label">服务商类型:</label>
            <a-select
              v-model:value="searchForm.providerType"
              placeholder="请选择服务商类型"
              class="search-select-large"
              allowClear
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="PAYMENT">支付服务商</a-select-option>
              <a-select-option value="TECH">技术服务商</a-select-option>
              <a-select-option value="INTEGRATED">综合服务商</a-select-option>
            </a-select>
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </div>

          <!-- 操作按钮 -->
          <div class="search-actions">
            <a-button type="primary" @click="handleSearch" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="search-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="providerTable"
            :autoLoad="true"
            :dataLoader="loadProviderData"
            :tableColumns="tableColumns"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            tableRowKey="providerId"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button type="primary" @click="handleAdd">
                  <PlusOutlined /> 新增服务商
                </a-button>
              </a-space>
            </template>
                  <template #tableCell="{ column, record }">
              <template v-if="column.key === 'providerType'">
                <a-tag :color="getProviderTypeColor(record.providerType)">
                  {{ getProviderTypeText(record.providerType) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="record.status === 1 ? 'success' : 'default'">
                  {{ record.status === 1 ? '启用' : '禁用' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <div class="anypay-apple-actions">
                  <a-space>
                    <a-button type="link" @click="handleChannelConfig(record)">支付渠道配置</a-button>
                    <a-button type="link" @click="handleOAuthConfig(record)">开放授权配置</a-button>
                    <a-dropdown placement="bottomRight">
                      <a-button type="link" size="small">
                        <MoreOutlined />
                        更多
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="edit" @click="handleEdit(record)">
                            <EditOutlined />
                            编辑
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item key="delete" @click="handleDelete(record)" style="color: #ff4d4f;">
                            <DeleteOutlined />
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- 子组件 -->
    <ServiceProviderEdit
      v-model:visible="editVisible"
      :service-provider="currentProvider"
      @success="handleEditSuccess"
    />

    <ChannelConfig
      v-model:visible="channelConfigVisible"
      :provider="currentProvider"
      @success="handleChannelConfigSuccess"
    />

    <OAuthConfig
      v-model:visible="oauthConfigVisible"
      :provider="currentProvider"
      @success="handleOAuthConfigSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, MoreOutlined } from '@ant-design/icons-vue'
import {
  mockLoadProviders,
  type ServiceProvider
} from '@/mock/service-providers'
// 子组件导入
import ServiceProviderEdit from './components/ServiceProviderEdit.vue'
import ChannelConfig from './components/ChannelConfig.vue'
import OAuthConfig from './components/OAuthConfig.vue'
import AnyTable from '@/components/AnyTable.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref<ServiceProvider[]>([])
const currentProvider = ref<ServiceProvider | null>(null)
const editVisible = ref(false)
const channelConfigVisible = ref(false)
const oauthConfigVisible = ref(false)

// 组件引用
const providerTable = ref()

// 搜索表单
const searchForm = reactive({
  providerName: '',
  providerType: '',
  status: undefined as number | undefined
})

// 搜索参数
const searchParams = reactive<{
  providerName?: string
  providerType?: string
  status?: number
}>({})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 表格列定义
const tableColumns = [
  {
    title: '服务商ID',
    dataIndex: 'providerId',
    key: 'providerId',
    width: 150
  },
  {
    title: '服务商名称',
    dataIndex: 'providerName',
    key: 'providerName',
    width: 200
  },
  {
    title: '服务商类型',
    dataIndex: 'providerType',
    key: 'providerType',
    width: 120,
    align: 'center'
  },
  {
    title: '联系人',
    dataIndex: 'contactPerson',
    key: 'contactPerson',
    width: 120
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone',
    key: 'contactPhone',
    width: 150
  },
  {
    title: '联系邮箱',
    dataIndex: 'contactEmail',
    key: 'contactEmail',
    width: 200,
    visible: false
  },
  {
    title: '商户数量',
    dataIndex: 'merchantCount',
    key: 'merchantCount',
    width: 100,
    align: 'center',
    visible: false
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 320,
    align: 'center',
    fixed: 'right'
  }
]

// 数据加载函数
const loadProviderData = async (params: any) => {
  try {
    const response = await mockLoadProviders({
      current: params.pageNumber || 1,
      pageSize: params.pageSize || 10,
      ...params
    }) as any

    return {
      records: response.data || [],
      total: response.total || 0,
      pageNumber: params.pageNumber || 1,
      pageSize: params.pageSize || 10
    }
  } catch (error) {
    console.error('Failed to load provider data:', error)
    return { records: [], total: 0, pageNumber: 1, pageSize: 10 }
  }
}

// 加载完成回调
const handleLoadComplete = () => {
  console.log('Provider data loaded successfully')
}

const handleSearch = () => {
  // 清空之前的搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  // 只添加非空的搜索条件
  if (searchForm.providerName) {
    searchParams.providerName = searchForm.providerName
  }
  if (searchForm.providerType) {
    searchParams.providerType = searchForm.providerType
  }
  if (searchForm.status !== undefined) {
    searchParams.status = searchForm.status
  }

  searchProviders()
}

const handleReset = () => {
  // 清空搜索表单
  Object.assign(searchForm, {
    providerName: '',
    providerType: '',
    status: undefined
  })

  // 清空搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  searchProviders()
}

// 搜索服务商
const searchProviders = () => {
  providerTable.value?.refreshTable(true)
}

const handleAdd = () => {
  currentProvider.value = null
  editVisible.value = true
}

const handleEdit = (row: ServiceProvider) => {
  currentProvider.value = row
  editVisible.value = true
}

const handleChannelConfig = (row: ServiceProvider) => {
  currentProvider.value = row
  channelConfigVisible.value = true
}

const handleOAuthConfig = (row: ServiceProvider) => {
  currentProvider.value = row
  oauthConfigVisible.value = true
}

const handleDelete = (row: ServiceProvider) => {
  message.info('删除功能开发中...')
}

// 子组件成功回调函数
const handleEditSuccess = () => {
  searchProviders()
}

const handleChannelConfigSuccess = () => {
  searchProviders()
}

const handleOAuthConfigSuccess = () => {
  searchProviders()
}

const getProviderTypeColor = (type: string) => {
  const colors = {
    PAYMENT: 'blue',
    TECH: 'green',
    INTEGRATED: 'purple'
  }
  return colors[type as keyof typeof colors] || 'default'
}

const getProviderTypeText = (type: string) => {
  const texts = {
    PAYMENT: '支付服务商',
    TECH: '技术服务商',
    INTEGRATED: '综合服务商'
  }
  return texts[type as keyof typeof texts] || type
}

// loadData 和 onMounted 已由 AnyTable 的 autoLoad 处理
</script>

<style scoped>
@import '../common/list-page.css';
</style>